import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sjx/pages/task/publish/item/task_publish_item_vm.dart';
import 'package:sjx/repository/model/user_task_publish_order_list.dart';
import 'package:sjx/route/route_utils.dart';
import 'package:sjx/route/routes.dart';

import '../../../../common_ui/smart_refresh/smart_refresh_widget.dart';
import '../../../../repository/model/home_list_model.dart';
import '../../../../repository/model/type_and_tag_icon.dart';
import '../../../../repository/model/user_task_order_list.dart';
import '../../../../utils/empty_widget.dart';

class PublishTaskItemPage extends StatefulWidget {
  final int type;
  final ValueNotifier<int>? countNotifier;

  const PublishTaskItemPage({Key? key, required this.type, this.countNotifier}) : super(key: key);

  @override
  _PublishTaskItemPageState createState() => _PublishTaskItemPageState();
}

class _PublishTaskItemPageState extends State<PublishTaskItemPage> {
  late final TaskPublishItemViewModel _viewModel = TaskPublishItemViewModel();
  late RefreshController _refreshController;

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: false);
    _viewModel.statusType = widget.type;
    // 监听ViewModel的数量变化
    _viewModel.addListener(_onViewModelChanged);
    _viewModel.initDataList(false);
  }

  void _onViewModelChanged() {
    // 当ViewModel的数量更新时，通知父组件
    if (widget.countNotifier != null) {
      widget.countNotifier!.value = _viewModel.itemCount;
    }
  }

  void refreshOrLoad(bool loadMore) {
    _viewModel.initDataList(
      loadMore,
      complete: (loadMore) {
        if (loadMore) {
          _refreshController.loadComplete();
        } else {
          _refreshController.refreshCompleted();
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return _viewModel;
      },
      child: Consumer<TaskPublishItemViewModel>(
        builder: (context, value, child) {
          return Scaffold(
            backgroundColor: Colors.white,
            body: SafeArea(
              child: SmartRefreshWidget(
                controller: _refreshController,
                onLoading: () {
                  refreshOrLoad(true);
                },
                onRefresh: () {
                  refreshOrLoad(false);
                },
                child: _buildContent(value),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildContent(TaskPublishItemViewModel viewModel) {

    if (viewModel.listData!.isEmpty) {
      return const EmptyWidget(
        message: "暂无任务",
        imagePath: "assets/images/error_nodata.png",
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(0),
      itemCount: viewModel.listData!.length,
      itemBuilder: (context, index) {
        final item = viewModel.listData![index];
        return _buildTaskItem(item);
      },
    );
  }

  Widget _buildTaskItem(UserPublishTaskOrderList item) {
    return GestureDetector(
      onTap:() => _viewModel.onViewTask(context, item.taskNo),
      child: Container(
        padding: const EdgeInsets.all(15),
        decoration: const BoxDecoration(
          border: Border(bottom: BorderSide(color: Color(0xFFEEEEEE), width: 0.5)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 任务图标
                Container(
                  width: 48,
                  height: 48,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5),
                    color: const Color(0xFFF5F5F5),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(5),
                    child: CachedNetworkImage(
                      imageUrl: item.taskThumb ?? "",
                      placeholder: (context, url) => const Icon(Icons.photo, color: Colors.grey),
                      errorWidget: (context, url, error) {
                        return Image.asset(
                          'assets/images/header.png',
                          width: 48.h,
                          height: 48.h,
                          fit: BoxFit.cover,
                        );
                      },
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 标题和标签区域
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              item.taskTitle ?? "未知任务",
                              style: const TextStyle(
                                fontSize: 15,
                                fontWeight: FontWeight.w500,
                                color: Color(0xFF333333),
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      // 标签区域
                      _buildTagIcons(item),
                      const SizedBox(height: 4),
                      // 描述
                      Text(
                        item.taskDescriptionInfo ?? "暂无描述",
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF999999),
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            // 按钮区域
            _buildButtonArea(item),
          ],
        ),
      ),
    );
  }

  Widget _buildTagIcons(UserPublishTaskOrderList item) {
    // 这里需要根据实际数据结构调整
    final tags = item.typeAndTagIcons ?? [];
    if (tags.isEmpty) {
      return const SizedBox.shrink();
    }

    return SizedBox(
      height: 21,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        itemCount: tags.length,
        separatorBuilder: (context, index) => const SizedBox(width: 8),
        itemBuilder: (context, index) {
          final tag = tags[index] as TypeAndTagIcon;
          return CachedNetworkImage(
            imageUrl: tag.imageUrl ?? "",
            width: tag.width.toDouble() ?? 31,
            height: 16,
            placeholder: (context, url) => Container(
              width: tag.width.toDouble() ?? 31,
              height: 16,
              color: Colors.grey[200],
            ),
            errorWidget: (context, url, error) => Container(
              width: tag.width.toDouble() ?? 31,
              height: 16,
              color: Colors.grey[200],
            ),
          );
        },
      ),
    );
  }

  Widget _buildButtonArea(UserPublishTaskOrderList item) {
    final status = widget.type;
    final buttons = <Widget>[];

    switch (status) {
      case 0:
        buttons.addAll([

          _buildActionButton("删除任务", Colors.grey, () => _onDeleteTask(item)),
          const SizedBox(width: 10),
          _buildActionButton("查看任务", Theme.of(context).primaryColor, () => _onShowTask(item)),
        ]);
        break;
      case 1:
        buttons.addAll([
          _buildActionButton("去付款", Theme.of(context).primaryColor, () => _onPayTask(item)),
          const SizedBox(width: 10),
          _buildActionButton("删除任务", Colors.grey, () => _onDeleteTask(item)),
          const SizedBox(width: 10),
          _buildActionButton("重新提交", Theme.of(context).primaryColor, () => _onSubmitTask(item)),
        ]);
        break;
      case 2:
        buttons.addAll([
          _buildActionButton("结束任务", Colors.grey, () => _onEndTask(item)),
          const SizedBox(width: 10),
          _buildActionButton("查看提交结果", Theme.of(context).primaryColor, () => _onShowSubmitTask(item)),
        ]);
        break;
      case 3:
        buttons.addAll([
          _buildActionButton("重新发布", Colors.grey, () => _onAgainCreateTask(item)),
          const SizedBox(width: 10),
          _buildActionButton("查看提交结果", Theme.of(context).primaryColor, () => _onShowSubmitTask(item)),
        ]);
        break;
      case 4:
        buttons.addAll([
          _buildActionButton("删除任务", Colors.grey, () => _onDeleteTask(item)),
          const SizedBox(width: 10),
          _buildActionButton("重新发布", Colors.grey, () => _onAgainCreateTask(item)),
          const SizedBox(width: 10),
          _buildActionButton("查看提交结果", Theme.of(context).primaryColor, () => _onShowSubmitTask(item)),
        ]);
        break;
      case 5:
        buttons.addAll([
          _buildActionButton("修改任务", Colors.grey, () => _onEditTask(item)),
          const SizedBox(width: 10),
          _buildActionButton("查看任务", Theme.of(context).primaryColor, () => _onShowTask(item)),
        ]);
        break;
      default:
        buttons.add(_buildActionButton("查看任务", Theme.of(context).primaryColor, () => _onShowTask(item)));
    }

    return Align(
      alignment: Alignment.centerRight,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: buttons,
      ),
    );
  }

  Widget _buildActionButton(String text, Color color, VoidCallback? onPressed,
      {bool enabled = true}) {
    return OutlinedButton(
      onPressed: enabled ? onPressed : null,
      style: OutlinedButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        side: BorderSide(color: enabled ? color : Colors.grey),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(14),
        ),
        backgroundColor: Colors.transparent,
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 13,
          color: enabled ? color : Colors.grey,
        ),
      ),
    );
  }

  void _onEditTask(UserPublishTaskOrderList item) {
    // 修改任务
    RouteUtils.pushForNamed(context, RoutePath.task_create_fill_in, arguments: {'taskCategoryStr': item.taskCategory, 'againCreate': false, 'taskId': item.taskNo});
  }

  void _onAgainCreateTask(UserPublishTaskOrderList item) {
    // 重新发布任务
    RouteUtils.pushForNamed(context, RoutePath.task_create_fill_in, arguments: {'taskCategoryStr': item.taskCategory, 'againCreate': true, 'taskId': item.taskNo});
  }

  void _onEndTask(UserPublishTaskOrderList item) {
    // 结束任务
    _viewModel.onEndTask(context, item.taskNo);
  }

  void _onShowSubmitTask(UserPublishTaskOrderList item) {
    // 查看提交结果
    RouteUtils.pushForNamed(context, RoutePath.task_publish_examine, arguments: {'taskId': item.taskNo});
  }

  void _onPayTask(UserPublishTaskOrderList item) {
    // 支付任务
    RouteUtils.pushForNamed(context, RoutePath.task_pay, arguments: {
      'taskId': item.taskNo,
      'amountStr': item.taskAllRewardAmountDisplay,
      'refreshHandle': (){
        //支付成功，需要刷新页面
      _viewModel.initDataList(false);
      },
    });
  }

  void _onShowTask(UserPublishTaskOrderList item) {
    // 实现查看任务详情
    _viewModel.onEndTask(context, item.taskNo);
  }

  void _onDeleteTask(UserPublishTaskOrderList item) {
    // 实现删除任务逻辑
    _viewModel.onDeleteTask(context, item.taskNo);
  }

  void _onSubmitTask(UserPublishTaskOrderList item) {
    // 实现提交任务逻辑
    _viewModel.onSubmitTask(context, item.taskNo, item.taskNo);
  }

  void _onViewTask(UserPublishTaskOrderList item) {
    // 实现查看任务逻辑
    _viewModel.onViewTask(context, item.taskNo);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}
